const express=require("express");
const _=require("lodash");

let router=express.Router();

var cars=[];
cars.push({id:201701,name:"BMW",price:190,speed:"210km/h",color:"白色"});
cars.push({id:201702,name:"BYD",price:25,speed:"160km/h",color:"红色"});
cars.push({id:201703,name:"Benz",price:300,speed:"215km/h",color:"蓝色"});
cars.push({id:201704,name:"Honda",price:190,speed:"170km/h",color:"黑色"});
cars.push({id:201705,name:"QQ",price:130,speed:"210km/h",color:"白色"});

//Get请求，获取所有汽车
router.get("/",(req,res,next)=>{
    res.json({status:"ok","data":cars});
});
//Get请求，获取汽车通过编号
router.get("/:id",(req,res,next)=>{
    //查找编号为id的汽车
    let car=_.find(cars,{id:parseInt(req.params.id)});
    res.json({status:"ok","data":car});
});

//Post，添加汽车
router.post("/",(req,res,next)=>{
    let car=req.body;
    //获取编号最大的汽车
    let obj=_.last(_.sortBy(cars,["id"]));
    //最大的编号加1
    car.id=obj.id+1;
    cars.push(car);
    res.json({status:"ok","data":car});
});

//Put请求,修改汽车
router.put("/",(req,res,next)=>{
    let srcCar=req.body;
    //查找编号为id的汽车
    let car=_.find(cars,{id:parseInt(srcCar.id)});
    //修改
    car.name=srcCar.name;
    car.speed=srcCar.speed;
    car.price=srcCar.price;
    car.color=srcCar.color;
    res.json({status:"ok","data":cars});
});

//Delete请求,删除汽车
router.delete("/:id",(req,res,next)=>{
    let srcCar=req.body;
    //查找编号为id的汽车索引号
    let index=_.findIndex(cars,{id:parseInt(req.params.id)});
    //从cars数组中删除指定编号的元素
    cars.splice(index,1);
    res.json({status:"ok","data":req.params.id});
});


module.exports=router;